<template>
  <div class="tpl-container">
    <div class="mb20 condition-container">
      <div class="condition">
        <span class="color_494949 ft12 pr5">彩屏标识：</span>
        <ElInput
          v-model="UUID"
          class="w164 mr14"
          placeholder="请输入彩屏编码"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">组合编码：</span>
        <ElInput
          v-model="csCode"
          class="w164 mr14"
          placeholder="请输入组合编码"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">正反面：</span>
        <!-- <ElInput v-model="csName" class="w164" placeholder="请输入正反面" /> -->
        <el-select v-model="csName" class="m-2 w164" placeholder="Select">
          <el-option
            v-for="item in csNames"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">出库状态：</span>
        <el-select v-model="Status" class="m-2 w164" placeholder="Select">
          <el-option
            v-for="item in statusArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">屏幕类型：</span>
        <el-select v-model="LCDType" class="m-2 w164" placeholder="Select">
          <el-option
            v-for="item in lcdTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">箱号：</span>
        <ElInput v-model="Remark" class="w164 mr14" placeholder="请输入箱号" />
      </div>
      <div class="condition">
        <ElButton class="settingBtn" type="primary" @click="search">
          查询
        </ElButton>
        <ElButton class="settingBtn" type="primary" @click="exportList">
          导出商品
        </ElButton>
        <el-upload
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :action="action"
          :before-upload="beforeUpload"
          class="ml"
          :headers="headers"
          name="fileInput"
          :on-error="handleError"
          :on-success="handleSuccess"
          :show-file-list="false"
        >
          <ElButton type="primary">导入商品</ElButton>
        </el-upload>
        <ElButton
          class="settingBtn ml"
          type="primary"
          @click="downLoadTemplate"
        >
          下载模板
        </ElButton>
      </div>
    </div>
    <div class="btns">
      <Tabs
        :company-list="nameList"
        :multiple-selection="multipleSelection"
        @add-cs-confirm="addCsDialogHandleConfirm"
        @add-double-cs-confirm="addDoubleCsDialogHandleConfirm"
        @confirm="dialogConfirm"
      />
    </div>
    <div class="table">
      <ElTable
        ref="multipleTableRef"
        v-loading="loading"
        :border="true"
        :data="tableData"
        @selection-change="handleSelectionChange"
      >
        <ElTableColumn type="selection" width="55" />
        <ElTableColumn label="彩屏标识" prop="UUID" width="auto" />
        <ElTableColumn label="组合编码" prop="CSCode" width="auto" />
        <ElTableColumn label="正反面" prop="CSName" width="auto" />
        <ElTableColumn label="彩屏类型">
          <template #default="{ row }">
            <div>
              {{
                row.LCDType == '00'
                  ? '600*1024'
                  : row.LCDType == '01'
                  ? '600*664'
                  : row.LCDType == '02'
                  ? '600*620'
                  : row.LCDType == '10'
                  ? '1024*600'
                  : row.LCDType == '11'
                  ? '664*600'
                  : row.LCDType == '12'
                  ? '620*600'
                  : row.LCDType == '03'
                  ? '800*1280'
                  : ''
              }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="版本号" prop="Version" width="auto" />
        <ElTableColumn label="箱号" prop="Remark" width="auto" />
        <ElTableColumn label="状态">
          <template #default="{ row }">
            <div>
              {{ row.Status == 0 ? '异常' : '正常' }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="出库公司" prop="CompanyName" width="auto" />
        <ElTableColumn label="出库时间" prop="OutStockDate" width="auto" />
        <ElTableColumn label="出库状态">
          <template #default="{ row }">
            <div>
              {{ row.StockStatus == 0 ? '未出库' : '已出库' }}
            </div>
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn label="归属商户" prop="CompanyId" width="auto" /> -->
        <ElTableColumn label="创建时间" prop="CreateDate" width="auto" />
        <ElTableColumn label="操作" width="200">
          <template #default="{ row }">
            <ElButton
              v-if="MenuAuth('edit')"
              link
              type="primary"
              @click="editFn(row)"
            >
              修改
            </ElButton>
            <ElButton
              v-if="MenuAuth('delete')"
              link
              type="danger"
              @click="deleteFn(row)"
            >
              删除
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      <div v-if="total > 0" class="pagination">
        <ElPagination
          background
          :current-page="searchInfo.pageNo"
          :layout="layout"
          :page-size="searchInfo.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <Dialog
      :fields="dialogFields"
      :title="dialogTitle"
      :visible="dialogVisible"
      @close="handleClose"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { MenuAuth } from '~/src/utils/permission'
  import {
    getStockPageData,
    deltemp,
    GetCompany,
    getcss,
    csstockedit,
    StockExport,
    StockDownLoadTemplate,
  } from '@/api/mupro'
  import router from '@/router'
  import { useEleStore } from '@/store/modules/coms'
  import Tabs from './components/tabs.vue'
  import { save } from './components/save'
  import Dialog from '../components/dialog.vue'
  import { formFileds } from './components/form'
  import { baseURL } from '@/config'
  import { parseTime } from '@/utils'
  import { useUserStore } from '@/store/modules/user'
  const csCode = ref('')
  const csName = ref('')
  const UUID = ref('')
  const Status: any = ref('')
  const LCDType: any = ref('')
  const Remark: any = ref('')
  const searchInfo = reactive({
    pageNo: 1,
    pageSize: 20,
    tableName: '',
    sort: '',
    order: '',
    wheres: `[{"name":"CSCode","value":${csCode.value},"displayType":"like"}, {"name":"CSName","value":${csName.value},"displayType":"like"}, {"name":"UUID","value":${UUID.value},"displayType":"like"}, {"name":"Status","value":${Status.value},"displayType":"like"}, {"name":"LCDType","value":${LCDType.value},"displayType":"like"}, {"name":"Remark","value":${Remark.value},"displayType":"like"}]`,
    export: false,
    value: '',
  })
  const statusArr: any = ref([
    {
      label: '全部',
      value: '',
    },
    {
      label: '未出库',
      value: '0',
    },
    {
      label: '已出库',
      value: '1',
    },
  ])
  const lcdTypes: any = ref([
    {
      label: '全部',
      value: '',
    },
    {
      label: '600*1024',
      value: '00',
    },
    {
      label: '800*1280',
      value: '03',
    },
    // {
    //   label: '600*664',
    //   value: '01',
    // },
    // {
    //   label: '600*620',
    //   value: '02',
    // },
    // {
    //   label: '1024*600',
    //   value: '10',
    // },
    // {
    //   label: '664*600',
    //   value: '11',
    // },
    // {
    //   label: '620*600',
    //   value: '12',
    // },
  ])
  const csNames = [
    {
      label: '全部',
      value: '',
    },
    {
      label: '正面',
      value: '正面',
    },
    {
      label: '反面',
      value: '反面',
    },
  ]
  const nameList: any = ref([])
  const loading = ref(false)
  const { clearWidgets, clearEditorData } = useEleStore()
  const getCompanyList = async () => {
    const { data } = await GetCompany({
      pageNo: 0,
      pageSize: 0,
      total: 0,
      tableName: 'string',
      sort: 'string',
      order: 'string',
      wheres: 'string',
      export: true,
      value: 'string',
    })
    nameList.value = data.rows
  }
  getCompanyList()

  const layout = ref('total, sizes, prev, pager, next, jumper')
  const tableData = ref([])
  const total = ref(0)
  // 获取表格数据
  const gettableData = async () => {
    loading.value = true
    const { data } = await getStockPageData(searchInfo)
    loading.value = false
    // console.log(data)
    tableData.value = data?.rows || []
    total.value = data?.total || 0
  }
  gettableData()
  //分页条数切换
  const handleSizeChange = (val: any) => {
    searchInfo.pageSize = val
    gettableData()
  }
  //分页切换
  const handleCurrentChange = (val: any) => {
    searchInfo.pageNo = val
    gettableData()
  }

  const search = () => {
    searchInfo.pageNo = 1
    if (
      csCode.value.trim() !== '' ||
      csName.value.trim() !== '' ||
      UUID.value.trim() !== '' ||
      Status.value.trim() !== '' ||
      LCDType.value.trim() !== '' ||
      Remark.value.trim() !== ''
    ) {
      const arr = []
      csCode.value.trim() !== '' &&
        arr.push({ name: 'CSCode', value: csCode.value, displayType: 'like' })
      csName.value.trim() !== '' &&
        arr.push({ name: 'CSName', value: csName.value, displayType: 'like' })
      UUID.value.trim() !== '' &&
        arr.push({ name: 'UUID', value: UUID.value, displayType: 'like' })
      Status.value.trim() !== '' &&
        arr.push({ name: 'status', value: Status.value, displayType: 'like' })
      LCDType.value.trim() !== '' &&
        arr.push({ name: 'LCDType', value: LCDType.value, displayType: 'like' })
      Remark.value.trim() !== '' &&
        arr.push({ name: 'Remark', value: Remark.value, displayType: 'like' })
      searchInfo.wheres = JSON.stringify(arr)
    } else {
      searchInfo.wheres = `[{"name":"CSCode","value": '',"displayType":"like"}, {"name":"CSName","value": '',"displayType":"like"}, {"name":"UUID","value": '',"displayType":"like"}, {"name":"Status","value": '',"displayType":"like"}, {"name":"LCDType","value": '',"displayType":"like"}, {"name":"Remark","value": '',"displayType":"like"}]`
    }
    gettableData()
  }
  const $baseConfirm = inject('$baseConfirm') as any
  const deleteFn = async (row: any) => {
    $baseConfirm('你确定要删除当前项吗', null, async () => {
      await deltemp({
        id: row.ID,
      })
      gettableData()
    })
  }
  const multipleSelection = ref<any[]>([])
  const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val
  }
  const dialogConfirm = async (
    result: Array<any>,
    type: string,
    multipleSelection: Array<any>
  ) => {
    const data = await save(result, type, multipleSelection)
    gettableData()
  }
  // 编辑
  const dialogFields: any = ref([])
  const dialogTitle = '编辑'
  const dialogVisible = ref(false)
  const ID: any = ref(0)
  const editFn = async (row: any) => {
    ID.value = row.ID
    const {
      data: { data },
    } = await getcss({ id: row.ID })
    const formFiledsData = JSON.parse(JSON.stringify(formFileds))
    formFiledsData.add.map((item: any) => {
      item.model = data[item.field]
      if (item.field === 'switch') {
        item.model = data[item.field] === 1
      }
    })
    dialogFields.value = formFiledsData.add
    dialogVisible.value = true
  }
  const handleConfirm = async (
    result: any,
    type: string,
    multipleSelection: any
  ) => {
    const params: any = {}
    result.map((item: any) => {
      params[item.field] = item.model
    })
    params.status = params.status ? 1 : 0
    params.ID = ID.value
    await csstockedit(params)
    gettableData()
    dialogVisible.value = false
  }
  const handleClose = () => {
    dialogVisible.value = false
  }
  const addCsDialogHandleConfirm = () => {
    gettableData()
  }
  const addDoubleCsDialogHandleConfirm = () => {
    gettableData()
  }
  // 导出
  const exportList = async () => {
    loading.value = true
    const data = await StockExport(searchInfo)
    const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
    downloadFile(data, `库存信息${time}`)
    loading.value = false
  }
  // 下载模板
  const downLoadTemplate = async () => {
    const data = await StockDownLoadTemplate()
    const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
    downloadFile(data, `库存模板${time}`)
  }
  // 下载文件
  const downloadFile = async (data: any, name: string) => {
    const blob = new Blob([data])
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.download = `${name}.xlsx`
    link.href = url
    link.click()
  }
  // 导入商品
  const { token } = useUserStore()
  const headers = reactive({ Authorization: `Bearer ${token}` })
  const action = ref(`${baseURL}/CSStock/Import`)
  const beforeUpload = () => {}
  const handleSuccess = async (response: any) => {
    if (response.code == 200) {
      gettableData()
    } else {
      let message = response.message
      if (response.code === '-1') {
        message = `${JSON.parse(response.data)?.join(',')}${message}`
      }
      ElMessage.error(message)
    }
  }
  const handleError = () => {}
</script>

<style lang="scss" scoped>
  .tpl-container {
    .color_494949 {
      color: #494949;
    }

    .noData {
      text-align: center;
      font-size: 16px;
      color: gray;
    }
    .w164 {
      width: 164px;
    }
    .mb20 {
      margin-bottom: 20px;
    }

    .img-container {
      display: flex;
      // justify-content: center;

      .img {
        width: 100px;
      }
    }

    .condition-container {
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      .condition {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        margin-right: 14px;
        margin-bottom: 12px;
      }
    }

    .ml {
      margin-left: 10px;
    }
  }
  .el-table {
    & ::v-deep th.el-table__cell,
    ::v-deep td.el-table__cell {
      // 设置position 使得 子元素不与其产生新的层叠关系
      position: static;
    }
  }
</style>
